/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.applink.sell_proof;

import java.util.regex.Pattern;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.applink.sell_proof.constant.NotificationKey;
import com.applink.sell_proof.util.Utility;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;

/**
 * IntentService responsible for handling GCM messages.
 */
public class GCMIntentService extends GCMBaseIntentService {

	private Context mContext;
	private String message;
	private String contact;
	private static final String TAG = "GCMIntentService";
	private NotificationManager mNotification;
	private Notification note;

	public GCMIntentService() {
		super(Config.GCM_SENDER_ID);
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {
		Log.i(TAG, "Device registered: regId = " + registrationId);
		// DataHelper.getInstance().registerCGM(registrationId);
		mContext = this;
	}

	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Log.i(TAG, "Device unregistered");
		if (GCMRegistrar.isRegisteredOnServer(context)) {
		} else {
			// This callback results from the call to unregister made on
			// ServerUtilities when the registration to the server failed.
			Log.i(TAG, "Ignoring unregister callback");
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onMessage(Context context, Intent intent) {
		message = intent.getStringExtra(NotificationKey.MESSAGE);
		contact = intent.getStringExtra(NotificationKey.CONTACT);
		System.out.println("context1 " + contact);
		System.out.println("context2 " + Integer.parseInt((EMarketing.getInstance().getContactID())));
		if ((message!= null) && (message.length() > 0 && contact.length() > 0)) {		
			String[] parts = Pattern.compile(",", Pattern.LITERAL).split(contact);
			for(int x = 0;x < parts.length;x ++){			
				if (Integer.parseInt(parts[x].toString().trim())==Integer.parseInt((EMarketing.getInstance().getContactID()))) {
					
					if (message.equals("pricebook")) {
						Utility.checkGetLastestPriceBook = true;
						showNotification(0);
						note.flags |= Notification.FLAG_AUTO_CANCEL
								| Notification.FLAG_SHOW_LIGHTS;
						PendingIntent i = PendingIntent.getActivity(
								getApplicationContext(), 0, new Intent(
										getApplicationContext(),
										PriceBookActivity.class), 0);
						note.setLatestEventInfo(getApplicationContext(),
								"SellProof", " Please get the latest PriceBook", i);
						mNotification.notify(0, note);
					} else if (message.equals("promotion")) {
						Utility.checkGetLastestPromotion = true;
						showNotification(1);
						note.flags |= Notification.FLAG_AUTO_CANCEL
								| Notification.FLAG_SHOW_LIGHTS;
						PendingIntent i = PendingIntent.getActivity(
								getApplicationContext(), 0, new Intent(
										getApplicationContext(),
										NewPromotionActivity.class), 0);
						note.setLatestEventInfo(getApplicationContext(),
								"SellProof", " Please get the latest Promition", i);
						mNotification.notify(1, note);
					} else if (message.contains("claim")) {
						showNotification(1);
						note.flags |= Notification.FLAG_AUTO_CANCEL
								| Notification.FLAG_SHOW_LIGHTS;
						PendingIntent i = PendingIntent.getActivity(
								getApplicationContext(), 0, new Intent(
										getApplicationContext(),
										ClaimActivity.class), 0);
						note.setLatestEventInfo(getApplicationContext(),
								"SellProof", " Please get the latest Claim", i);
						mNotification.notify(1, note);
					}else if (message.equals("tip")) {
						Intent intentTip = new Intent(getApplicationContext(), LearnActivity.class);
						//intentTip.putExtra("push", false);
						showNotification(2);
						note.flags |= Notification.FLAG_AUTO_CANCEL
								| Notification.FLAG_SHOW_LIGHTS;
						PendingIntent i = PendingIntent.getActivity(
								getApplicationContext(), 0, intentTip, 0);
						note.setLatestEventInfo(getApplicationContext(),
								"SellProof", " Please get the latest Tip", i);
						mNotification.notify(2, note);
					}else if (message.equals("product")) {
						Utility.checkGetLastestProduct = true;
						showNotification(2);
						note.flags |= Notification.FLAG_AUTO_CANCEL
								| Notification.FLAG_SHOW_LIGHTS;
						PendingIntent i = PendingIntent.getActivity(
								getApplicationContext(), 0, new Intent(
										getApplicationContext(),
										ProductActivity.class), 0);
						note.setLatestEventInfo(getApplicationContext(),
								"SellProof", " Please get the latest Product", i);
						mNotification.notify(2, note);
					}else if (message.equals("quiz")) {
						Utility.checkPushQuiz = true;
						Intent intentQuiz = new Intent(getApplicationContext(), LearnActivity.class);
						//intentQuiz.putExtra("push", true);
						showNotification(2);
						note.flags |= Notification.FLAG_AUTO_CANCEL
								| Notification.FLAG_SHOW_LIGHTS;
						PendingIntent i = PendingIntent.getActivity(
								getApplicationContext(), 0, intentQuiz, 0);
						note.setLatestEventInfo(getApplicationContext(),
								"SellProof", " Please get the latest Quiz", i);
						mNotification.notify(2, note);
					}
				}
			}
			
		}
		Log.e(TAG,
				"onMessage " + intent.getStringExtra(NotificationKey.MESSAGE));
		Log.e(TAG,
				"onContact " + intent.getStringExtra(NotificationKey.CONTACT));
		String type = intent.getStringExtra(NotificationKey.TYPE);
		if (type == null)
			return;
//		Intent intentForward = new Intent(
//				"com.google.android.c2dm.intent.RECEIVE_FORWARD");
//		intentForward.putExtras(intent.getExtras());
//		if (type.equals(TypeNotification.BIRTHDAY)) {
//			context.sendOrderedBroadcast(intentForward, null);
//		} else if (type.equals(TypeNotification.DEAL_CHANGE_STAGE)) {
//			String stage = intent.getStringExtra(NotificationKey.DEAL_STAGE);
//			String realDealId = intent.getStringExtra(NotificationKey.DEAL_ID);
//			Log.e(TAG, "deal id :" + realDealId);
//			Log.e(TAG, "deal stage: " + stage);
//			long realId = Long.parseLong(realDealId);
//			DealDBHelper.updateDealStage(realId, Integer.parseInt(stage));
//			context.sendOrderedBroadcast(intentForward, null);
//		} else if (type.equals(TypeNotification.TIP)) {
//			String tipId = intent.getStringExtra(NotificationKey.TIP_ID);
//			String paragraph = intent
//					.getStringExtra(NotificationKey.TIP_PARAGRAPH);
//			String category = intent
//					.getStringExtra(NotificationKey.TIP_CATEGORY);
//			String tip_name = intent.getStringExtra(NotificationKey.TIP_NAME);
//			Log.e(TAG, "tip id :" + tipId);
//			Log.e(TAG, "tip pargraph: " + paragraph);
//			Log.e(TAG, "tip category: " + category);
//			Log.e(TAG, "tip name: " + tip_name);
//
//			Tip tip = new Tip();
//			tip.setId(Long.parseLong(tipId));
//			tip.setName(tip_name);
//			int year = GregorianCalendar.getInstance().get(
//					GregorianCalendar.YEAR);
//			int month = GregorianCalendar.getInstance().get(
//					GregorianCalendar.MONTH);
//			int day = GregorianCalendar.getInstance().get(
//					GregorianCalendar.DATE);
//			tip.setDate(new GregorianCalendar(year, month, day)
//					.getTimeInMillis());
//			tip.setParagraph(paragraph);
//			tip.setCategory(Tip.Category.getCategory(Integer.parseInt(category)));
//			TipDBHelper.createTip(tip);
//			context.sendOrderedBroadcast(intentForward, null);
//		} else if (type.equals(TypeNotification.QUIZ)) {
//			String quizId = intent.getStringExtra(NotificationKey.QUIZ_ID);
//			String description = intent
//					.getStringExtra(NotificationKey.QUIZ_DESCRIPTION);
//			String name = intent.getStringExtra(NotificationKey.QUIZ_NAME);
//			String category = intent
//					.getStringExtra(NotificationKey.QUIZ_CATEGORY);
//			Log.e(TAG, "quiz id: " + quizId);
//			Log.e(TAG, "quiz description: " + description);
//			Log.e(TAG, "quiz name :" + name);
//			Log.e(TAG, "quiz category: " + category);
//			Quiz quiz = new Quiz();
//			quiz.setId(Long.parseLong(quizId));
//			quiz.setCategory(Quiz.Category.getCategory(Integer
//					.parseInt(category)));
//			quiz.setDescription(description);
//			quiz.setName(name);
//			try {
//				Date closeDate = new SimpleDateFormat("yyyy-MM-dd",
//						Locale.TAIWAN).parse(intent
//						.getStringExtra(NotificationKey.QUIZ_CLOSE_DATE));
//				quiz.setEndDate(closeDate.getTime());
//			} catch (ParseException e) {
//				Log.e(TAG, "wrong format close date quiz");
//			}
//			QuizDBHelper.createQuiz(quiz);
//			context.sendOrderedBroadcast(intentForward, null);
//		}

	}

	@Override
	protected void onDeletedMessages(Context context, int total) {
		Log.i(TAG, "Received deleted messages notification");
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.i(TAG, "Received error: " + errorId);
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		// log message
		Log.i(TAG, "Received recoverable error: " + errorId);
		return super.onRecoverableError(context, errorId);
	}

	private void showNotification(int id) {
		mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		note = new Notification(R.drawable.new_icon, "New Message Dell App",
				System.currentTimeMillis());

		// mNotification.cancel(id);
		// mgr.notify(1,note);

	}
}
